package com.hmall.order.task;

/**
 * @Description Ordertiming
 * @Author zhengyuan&junjun
 * @Date 2024-11-16
 */

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.hmall.common.dto.Item;
import com.hmall.common.dto.Stock;
import com.hmall.config.ItemConfig;
import com.hmall.order.mapper.OrderDetailMapper;
import com.hmall.order.mapper.OrderMapper;
import com.hmall.order.pojo.Order;
import com.hmall.order.pojo.OrderDetail;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 下单未支付超时30分钟后，订单就会取消。
 *
 * **/
@Component

public class Ordertiming {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Autowired
    private ItemConfig itemConfig;

    @Scheduled(cron = "0 0/1 * * * ?")  //定时每1分钟执行一次
    @Transactional(rollbackFor = Exception.class)
    public void  time30(){
        System.out.println("任务执行时间"+System.currentTimeMillis());
        //1.查询status为1（未支付），并且下单时间超过30分钟的   sql 两个时间差
        List<Order> orders = orderMapper.selectList(Wrappers.<Order>lambdaQuery().eq(Order::getStatus, 1)  //查询未支付
                .lt(Order::getCommentTime, LocalDateTime.now().minusMinutes(30)));//查询下单时间超过30分钟
          if (ObjectUtil.isEmpty(orders)){
              return;
          }
          orders.forEach(o->{
             //根据商品id、商品数量恢复库存
              OrderDetail orderDetail = orderDetailMapper.getById(o.getId());   //查询订单详情
              Stock stock = new Stock();
              stock.setItemId(orderDetail.getItemId());
              //根据id查询商品详情
              Item item = itemConfig.getbyId(stock.getItemId());
               //恢复库存数量
              stock.setNum(item.getStock()+orderDetail.getNum());
              itemConfig.stock(stock);
              //根据orderId修改订单status为5 （交易取消，订单关闭）
              Order orderupdate = new Order();
              orderupdate.setStatus(5);
              orderMapper.updateById(orderupdate);
          });




    }


}
